import requests
import re
import json

# 爬取快手视频
url = 'https://www.kuaishou.com/short-video/3x3vuuawuzqk43w?authorId=3xzq24vcxkthfx4&streamSource=find&area=homexxbrilliant'

headers = {
    'User-Agent':'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/127.0.0.0 Safari/537.36'
}

response = requests.get(url=url, headers=headers)
text = response.text
print(text)

# 使用正则Re表达式来获取指定标签值；
obj = re.compile(r'<script>window.__APOLLO_STATE__=(?P<data>.*?)</script>',re.S)
result = obj.finditer(text)
# print(result)  # <callable_iterator object at 0x0000023C8F367940>
for it in result:
    data = it.group('data')

# print(type(data))

index = data.find(';(function')
if index != -1:
    # 包含 ';(function' 则从当前包含索引位置~到结束，这段字符串全部删除；
    data = data[:index]
# 字符串转json
data_json = json.loads(data)
print(data_json)
# 获取json对象中的属性
_data = data_json['defaultClient']['VisionVideoDetailPhoto:3x3vuuawuzqk43w']['videoResource']['json']['h264']['adaptationSet'][0]['representation'][0]
# print(_data)
print(_data['url'])
# print(_data['backupUrl'])
# 视频访问地址
videoUrl = _data['url']
# 视频请求头封装
_headers = {
    'User-Agent':'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/127.0.0.0 Safari/537.36',
    'Referer': 'https://www.kuaishou.com/new-reco'
}
# 视频发起请求
videores = requests.get(url=videoUrl, headers=_headers)
videoContent = videores.content
# 将视频响应下载本地
with open('kuaishou.mp4', mode='wb') as fp:
    fp.write(videoContent)
print('success...')











'''
# B站实例
url = 'https://www.bilibili.com/video/BV1Uw4m1r7gC/?spm_id_from=333.1007.tianma.1-1-1.click&vd_source=573500880d5803186d2a544d4727234c'

headers = {
    'User-Agent':'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/127.0.0.0 Safari/537.36'
}

# 发起请求Get
response = requests.get(url=url, headers=headers)
content = response.text
# print(content)

obj = re.compile(r'<script>window.__playinfo__=(?P<data>.*?)</script>',re.S)
result = obj.finditer(content)
# print(result)  # <callable_iterator object at 0x0000023C8F367940>
for it in result:
    data = it.group('data')
print(data)
data_json = json.loads(data)
videosrcurl = data_json['data']['dash']['video'][0]['baseUrl']
musicsrcurl = data_json['data']['dash']['audio'][0]['baseUrl']
print('视频地址：', videosrcurl)
print('音频地址：', musicsrcurl)

_headers = {
    'User-Agent':'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/127.0.0.0 Safari/537.36',
    'Referer': 'https://www.bilibili.com/'
}
videores = requests.get(url=videosrcurl, headers=_headers)
videoContent = videores.content
with open('blibili.mp4', mode='wb') as fp:
    fp.write(videoContent)
print('success...')


'''